# -*- coding: utf-8 -*-
# @Time  : 2022/05/12 17:32
# @Author: masonsxu
# @File  : exception.py
# @Desc  : 捕捉系统错误日志

import asyncio
import traceback
from functools import wraps
from typing import Union

from web_app.infrastructure.utils.http.responser import send
from web_app.infrastructure.utils.common.logger import log_task_main


def exception_capture(seed_code: Union[int, bool] = 14003):
    """捕获异常输出到日志

    Args:
        seed_code (int, optional): 异常提示提示码. Defaults to 51000.
    """

    def except_execute(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                sign = '=' * 60 + '\n'
                msg = f'{sign}>>>异常接口：\t{func.__name__}\n>>>异常入参：\t{args, kwargs}\n>>>异常信息：\t{e}'
                msg_traceback = f'{sign}{traceback.format_exc()}{sign}'

                # 协程记录日志
                asyncio.run(log_task_main(f'\n{msg}\n{msg_traceback}', level='error'))

                # 判断是否为bool类型，是则直接返回
                if isinstance(seed_code, bool):
                    return seed_code

                # 判断需不需要返回报错代码
                elif seed_code is not None:
                    return send(seed_code)

        return wrapper

    return except_execute
